import requests
import json
from datetime import datetime
from distutils.util import strtobool
from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from common.notice_tools import NoticeTools
from app.notice_center.models.nc_n9e_alarm_record import NCN9eAlarmRecord
from app.notice_center.handlers.nc_n9e_alarm_handler import NCN9eAlarmHandler
from setting import config



class NCN9eCallbackCassandraRecoveryHandler():
    """  Self Healing Handler
    """
    def __init__(self):
        self.handle_url = config.FSR_CASSANDRA_RECOVERY_URL
        self.token = config.FSR_CASSANDRA_RECOVERY_TOKEN
        self.notice_tools = NoticeTools()



    def filter_alarm_info(self, data: dict):
        alarm_data = {
            "status": "resolved" if data["is_recovered"] else "firing",
        }
                
        return alarm_data


    def post_nc_n9e_heal_cassandra_recovery(self, db: Session, data: dict, token: str):
        try:
            logger.info(f"cassandra recovery 收到回调告警信息=>{data}")

            alarm_data = self.filter_alarm_info(data)

            # 前期数据判断
            if "" in list(alarm_data.values()):
                logger.error(f"cassandra recovery: value is null")
                return False
            
            if self.token != token:
                # token验证
                logger.error(f"cassandra recovery: token is error")
                return False
            
            if alarm_data["status"] == "resolved":
                logger.info(f"cassandra recovery: resolved 无处理")
                return True
                                
                    
            # 全局维护：不告警、不回调
            nc_n9e_alarm_handler = NCN9eAlarmHandler()
            global_record_info = NCN9eAlarmRecord.get_object_info_for_block_global(db)
            if global_record_info and not nc_n9e_alarm_handler.check_alert_notice_maintain(global_record_info):
                logger.info(f"container cpu usage: block alarm in global maintain")
                return True
                    
            # 处理cassandra删除异常任务的操作
            result = self.handle_cassandra_recovery()
            if not result:
                logger.error(f"handle cassandra recovery failed")
                return False

            logger.info(f"handle cassandra recovery success")
        except Exception as e:
            message = f"cassandra recovery callback error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True



    def handle_cassandra_recovery(self):
        headers = {
            "Content-Type": "application/json",
        }
        data = {
            "action": "kill"
        }

        try:
            # 回调扩缩容接口
            req = requests.post(url=self.handle_url, headers=headers, data=json.dumps(data), timeout=5)
            if req.status_code != 200:
                message = f"n9e故障自愈 => cassandra recovery 失败"
                logger.error(message)
            else:
                message = f"n9e故障自愈 => cassandra recovery 成功"
                logger.info(message)
        except Exception as e:
            message = f"n9e故障自愈 => cassandra recovery 异常"
            self.notice_tools.send_wechat_group(message)
            logger.exception(f"{message} error: {e}")
            return False

        # 发送处理结果信息到企业微信群
        self.notice_tools.send_wechat_group(message)

        return True


